// 账户体系模块处理函数

const utils = require("../common/utils")
const svgCaptcha = require("svg-captcha")
// 密码加密模块
const bcrypt = require('bcryptjs')
// 引入邮箱服务
const transporter = require('../config/smtp.js')
const server = require("../server/account")

// 注册
exports.register = (req, res) => {
  const {
    email,
    password,
    qrcode
  } = req.body;
  // 判断验证码
  server.getQrCode(email).then(result => {
    if (qrcode) {
      if (result == qrcode) {
        server.register(email, password).then(result1 => {
          if (result1 == '邮箱已被注册') return res.cc(result1)
          return res.cc(result1, 200)
        })
      } else {
        return res.cc("验证码错误，请重新输入")
      }
    } else {
      return res.cc("验证码无效，请重新获取")
    }   
  }).catch(err => {
    return res.cc(err)
  })
}

// 登录
exports.login = (req, res) => {
  let { email, password, qrcode } = req.body
  if (!email || !password) return res.cc('邮箱或密码不合法')
  // console.log(req.session);
  // if (qrcode.toLowerCase() != req.session.captcha) return res.cc("验证码错误")
  server.login(email, password).then(result => {
    return res.send({
      code: 200,
      message: '登录成功',
      data: {
        token: 'Bearer ' + result.token,
        indexPath: result.indexPath
      }
    })
  }).catch(err => {
    return res.cc(err)
  }) 
}

// 获取邮箱验证码
exports.qrECode = (req, res) => {
  let email = req.body.email;
  if (!email) return res.cc('请输入邮箱')
  let qrcode = utils.randomNumber()
  server.setQrCode(email, qrcode).then(result => {
    if (result) {
      transporter.sendMail({
        subject: '验证码',
        from: '1811082435@qq.com',
        to: email,
        text: `你好，你的验证码是：${qrcode}，请勿告知他人，以防个人信息泄露。`        
      }, (err, msg) => {
        if (err) return res.cc(err)
        return res.cc('验证码已发送', 200)
      })
    } else {
      return res.cc('验证码发送失败，请重试')
    }
  }).catch(e => {
    return res.cc(e)
  })  
}

// 获取图形验证码
exports.qrCode = (req, res) => {    
    const captcha = svgCaptcha.create({
      inverse: false,
      fontSize: 56,
      noise: 2,
      width: req.query.width || 150,
      height: req.query.height || 50,
      size: 4,
      ignoreChars: '0o1i',
      color: false,
      background: '#fff'
    })    
    // console.log(captcha.text);
    // res.cookie('captcha', captcha.text.toLowerCase()) 
    req.session.captcha = captcha.text.toLowerCase()
    res.type('svg')    
    res.send(captcha.data)
}